package study.ssm.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import study.ssm.entity.User;
import study.ssm.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequiredArgsConstructor
@RequestMapping
public class UserController {

    private final UserService userService;

    @GetMapping("/create")
    public String create() {
        return "create";
    }

    @GetMapping("/update")
    public String update(Integer id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "update";
    }


    @GetMapping(path = { "/", "/login"})
    public String login() {
        return "login";
    }

    @GetMapping("/register")
    public String register(Model model) {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        User one = userService.getByUsername(user.getUsername());
        if (one == null) {
            userService.create(user);
            return "redirect:/login";
        }
        return "redirect:/register";
    }


    @PostMapping("/login")
    public String login(User user, Model model, HttpSession session) {
        User one = userService.getByUsername(user.getUsername());
        if (one == null || !one.getPassword().equals(user.getPassword())) {
            return "redirect:/login";
        }
        session.setAttribute("loginUser", one);
        return "redirect:/product/list";
    }


    @PostMapping("/users/create")
    public String create(User user) {
        userService.create(user);
        return "redirect:/users/list";
    }

    @GetMapping("/users/remove")
    public String remove(Integer id) {
        userService.removeById(id);
        return "redirect:/users/list";
    }

    @PostMapping("/users/update")
    public String update(User user) {
        userService.update(user);
        return "redirect:/users/list";
    }

    @RequestMapping(path = { "/index", "/users/list"})
    public String list(User user, Model model) {
        List<User> list = userService.list(user);
        model.addAttribute("list", list);
        return "index";
    }

    @GetMapping("/users/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        User user = userService.getById(id);
        model.addAttribute("user", user);
        return "detail";
    }
}
